function AdvancedFindPlusButtonIsEnabled() {
    return false;
}

function AdvancedFindPlusButtonAdd() {
    if (window.top.isButtonAdd)
        return false;
    window.top.isButtonAdd = true;
    var cssWebResource = "pl_AdvancedFindPlusCss";
    var cssUrl = Xrm.Page.context.getClientUrl() + "/" + WEB_RESOURCE_ORG_VERSION_NUMBER + "/WebResources/" + cssWebResource;
    if (typeof (window.top.isAttachCss) == 'undefined') {
        window.top.isAttachCss = true;
        var css_link = window.top.$("<link>", {
            rel: "stylesheet",
            type: "text/css",
            href: cssUrl
        });
        css_link.appendTo('head');
    }
    if (window.top.$('#AdvancedFindPlus').length == 0) {
        AdvancedFindPlusButtonAdd2('AdvancedFindPlus', 'Advanced Find', "if (typeof(window.frames[0].AdvancedFindPlusNavigate)!='undefined') window.frames[0].AdvancedFindPlusNavigate()", 'AdvancedFindPlusImage');
    }
    window.top.isButtonAdd = false;
    return false;
}

function AdvancedFindPlusButtonAdd2(id, title, onclickJavascript, cssClass) {
    var button = $('<span class="navTabButton" style="display:none" id="' + id + '" title="' + title + '"><a class="navTabButtonLink" onkeypress="return true;" onclick="' + onclickJavascript + '" href="javascript:;" unselectable="on"><span class="navTabButtonImageContainer" unselectable="on"><img id="' + cssClass + '" class="' + cssClass + '" alt="" unselectable="on" src="/_imgs/NavBar/Invisible.gif"></span></span></a></span>');
    window.top.$('#GQC').before(button);
    button.fadeIn(1000);
}

function AdvancedFindPlusNavigate() {
    var url = "/main.aspx?pagetype=advancedfind";
    openStdWin(url, "_blank", 900, 600);
};

function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

function MscrmAdvancedFindShowResults() {    
    var total = _mainWindow.resultFrame.document.getElementById("crmGridControl_ItemsTotal");
    if (total != null) {
        var span = _mainWindow.resultFrame.document.createElement("span");
        if (total.innerHTML == "5000+" || total.innerHTML == "0") {
            var count = getMscrmAdvancedFindShowResultsCount();
            if (count == -1) count = "AggregateQueryRecordLimit exceeded";
            span.innerHTML = formatString("Total records: <strong>{0}</strong>", count);
        }
        else
            span.innerHTML = "Total records: <strong>" + total.innerHTML + "</strong>";
        var footer = _mainWindow.resultFrame.document.getElementById("crmGridControl_RecordSelectInfo");
        footer.appendChild(span);
    } else
        window.setTimeout(MscrmAdvancedFindShowResults, 100);
}

function getMscrmAdvancedFindShowResultsCount() {
    var sFetchXml = _mainWindow.$find("advFind").get_fetchXml();
    var oXmlDom = XUI.Xml.LoadXml(sFetchXml);
    var nodes = XUI.Xml.SelectNodes(oXmlDom, "/fetch/entity", null);
    var entity = nodes[0];
    var entityName = entity.getAttribute("name");
    sFetchXml = sFetchXml.replace(/"/g, "'");
    var pattern = /<order(\s*)attribute(\s*)=(\s*)'.*'(\s*) descending(\s*)=(\s*)('false'|'true')(\s*)\/>/g;
    sFetchXml = sFetchXml.replace(pattern, "");
    pattern = /<attribute(\s*)name(\s*)=(\s*)'\w*'(\s*)\/>/g;
    sFetchXml = sFetchXml.replace(pattern, "");
    var tmp = "<entity name='[entityName]'><attribute name='[entityName]id' aggregate='count' alias='count'/>";
    tmp = tmp.replace(/\[entityName\]/g, entityName);
    sFetchXml = sFetchXml.replace("<entity name='" + entityName + "'>", tmp);
    sFetchXml = sFetchXml.replace("<fetch ", "<fetch aggregate='true' ");
    try {
        var rows = XrmServiceToolkit.Soap.Fetch(sFetchXml);
        if (rows.length > 0)
            return numberWithCommas(rows[0].attributes['count'].value);
        else
            return 0;
    }
    catch (e){
        return -1;
    }
}

function getFetchXmlAdvancedFindShowResultsCount() {
    sFetchXml = sFetchXml.replace(/"/g, "'");
    var pattern = /<order(\s*)attribute(\s*)=(\s*)'.*'(\s*) descending(\s*)=(\s*)('false'|'true')(\s*)\/>/g;
    sFetchXml = sFetchXml.replace(pattern, "");
    pattern = /<attribute(\s*)name(\s*)=(\s*)'\w*'(\s*)\/>/g;
    sFetchXml = sFetchXml.replace(pattern, "");
    var tmp = "<entity name='[entityName]'><attribute name='[entityName]id' aggregate='count' alias='count'/>";
    tmp = tmp.replace(/\[entityName\]/g, entityName);
    sFetchXml = sFetchXml.replace("<entity name='" + entityName + "'>", tmp);
    sFetchXml = sFetchXml.replace("<fetch ", "<fetch aggregate='true' ");
    try{
        var rows = XrmServiceToolkit.Soap.Fetch(sFetchXml);
        if (rows.length > 0)
            return numberWithCommas(rows[0].attributes['count'].value);
        else
            return 0;
    }
    catch (e) {
        return -1;
    }
}

function AdvancedFindPlusCommandFetchXml() {
    var webresourceurl = "/WebResources/pl_AdvancedFindPlusHtml";
    var dialogwindow = new Mscrm.CrmDialog(Mscrm.CrmUri.create(webresourceurl), window, 800, 600);
    dialogwindow.setCallbackReference(function (result) {
        ExecuteFetchXmlQuery(result);
    });
    if (localStorage) {
        var advFind = _mainWindow.$find("advFind");
        var fetchXml = advFind.get_fetchXml();
        fetchXml = fetchXml.replace(/&#37;/g, "%");
        debugger;
        localStorage.setItem('CurrentFetchXml', fetchXml);
    }
    dialogwindow.show();
}

function getDefaultAdvancedFindSavedQueryId() {
    var fetchXml =
        [
"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>",
"  <entity name='savedquery'>",
"    <filter type='and'>",
"        <condition attribute='querytype' operator='eq' value='1' />",
"        <condition attribute='returnedtypecode' operator='eq' value='", objectTypeCode, "' />",
"    </filter>",
"  </entity>",
"</fetch>"
        ].join("");
    try{
        var rows = XrmServiceToolkit.Soap.Fetch(fetchXml);
        if (rows.length != 1)
            return "";
        var savedquery = rows[0];
        return "{" + savedquery.id.toUpperCase() + "}";
    }
    catch (e) {
        return "{00000000-0000-0000-0000-000000000000}";        
    }
}

function getLayoutXml(oXmlDom) {
    var cell = "<cell name='{0}' width='200'/>";
    var cells = "";
    var nodes = XUI.Xml.SelectNodes(oXmlDom, "/fetch/entity/attribute", null);
    if (nodes != null && nodes.length > 0) {
        for (var i = 0; i < nodes.length; i++) {
            cells += formatString(cell, nodes[i].getAttribute("name"));
        }
    }
    nodes = XUI.Xml.SelectNodes(oXmlDom, "/fetch/entity/link-entity", null);
    if (nodes != null && nodes.length > 0) {
        var cellLink = "<cell name='{0}.{1}' width='200' disableSorting='1'/>";
        for (var i = 0; i < nodes.length; i++) {
            var alias = nodes[i].getAttribute("alias");
            var subNodes = XUI.Xml.SelectNodes(oXmlDom, "/fetch/entity/link-entity[@alias='" + alias + "']/attribute", null);
            if (subNodes != null && subNodes.length > 0) {
                for (var j = 0; j < subNodes.length; j++) {
                    cells += formatString(cellLink, alias, subNodes[j].getAttribute("name"));
                }
            }
        }
    }
    var layoutXml = formatString("<grid name='resultset' object='{0}' jump='name' select='1' icon='1' preview='1'>", objectTypeCode);
    layoutXml += formatString("<row name='result' id='{0}id'>", entityName);
    layoutXml += cells;
    layoutXml += "</row></grid>";
    return layoutXml;
}

function getEntityName(oXmlDom) {
    var nodes = XUI.Xml.SelectNodes(oXmlDom, "/fetch/entity", null);
    if (nodes != null && nodes.length > 0) {
        var entity = nodes[0];
        return entity.getAttribute("name");
    }
    return "";
}

function ExecuteFetchXmlQuery(result) {
    var oXmlDom = XUI.Xml.LoadXml(result);
    entityName = getEntityName(oXmlDom);    
    objectTypeCode = XrmServiceToolkit.Common.GetObjectTypeCode(entityName);
    var layoutXml = getLayoutXml(oXmlDom);
    var savedQueryId = getDefaultAdvancedFindSavedQueryId();
    var advFind = _mainWindow.$find("advFind")
    advFind.Clear(false, false);
    oldEntityName = advFind.get_entityName();
    advFind.set_entityName(entityName);
    advFind.set_layoutXml(layoutXml);
    advFind.set_queryId(savedQueryId);
    advFind.set_queryObjectType(1039);
    sFetchXml = result;
    changeArea(ResultsPage);
    var resultRender = _mainWindow.$get("resultRender");
    $get("FetchXml", resultRender).value = sFetchXml;
    $get("LayoutXml", resultRender).value = advFind.get_layoutXml();
    $get("EntityName", resultRender).value = advFind.get_entityName();
    $get("DefaultAdvFindViewId", resultRender).value = savedQueryId;
    $get("ViewId", resultRender).value = advFind.get_queryId();
    $get("ViewType", resultRender).value = advFind.get_queryObjectType();
    if (_mainWindow._entityType === advFind.get_entityName()) {
        $get("UIProvider", resultRender).value = advFind.get_uiProvider();
        $get("DataProvider", resultRender).value = advFind.get_dataProvider();
    } else {
        $get("UIProvider", resultRender).value = "";
        $get("DataProvider", resultRender).value = "";
    }
    if (IsNull(XUI.Xml.GetParserError(oXmlDom)))
        $get("SortCol", resultRender).value = _mainWindow.GetOrderNodeAttrAndDirection(oXmlDom);
    var tmpSearchingMsg = "<table height='100%' width='100%' style='cursor:wait' class='ms-crm-Loading'><tr><td valign='middle' align='center' id='ExecutingSearchMessage'><img alt='' src='/_imgs/AdvFind/progress.gif'/><br>" + _mainWindow.LOCID_AF_EXECUTINGSEARCH + "</td></tr></table>", fetchResults = _mainWindow.resultFrame.document.getElementById("fetchResults");
    if (!IsNull(fetchResults)) {
        _mainWindow.resultFrame.XUI.Html.DomUtils.ForEachChild(fetchResults, _mainWindow.resultFrame.Function.createDelegate(this, function (child) {
            _mainWindow.resultFrame.Mscrm.Utilities.destroyElement(child);
        }));
        XUI.Html.SetOuterHTML(fetchResults, tmpSearchingMsg);
    } else
        _mainWindow.resultFrame.document.body.innerHTML = tmpSearchingMsg;
    window.setTimeout("_mainWindow.$get('resultRender').submit()", 10);
    window.setTimeout(FetchXmlAdvancedFindShowResults, 100);   
}

function FetchXmlAdvancedFindShowResults() {    
    var total = _mainWindow.resultFrame.document.getElementById("crmGridControl_ItemsTotal");
    if (total != null) {
        var span = _mainWindow.resultFrame.document.createElement("span");
        if (total.innerHTML == "5000+" || total.innerHTML == "0") {
            var count = getFetchXmlAdvancedFindShowResultsCount();
            if (count == -1) count = "AggregateQueryRecordLimit exceeded";
            span.innerHTML = formatString("Total records: <strong>{0}</strong>", count);
        }
        else
            span.innerHTML = "Total records: <strong>" + total.innerHTML + "</strong>";
        var footer = _mainWindow.resultFrame.document.getElementById("crmGridControl_RecordSelectInfo");
        footer.appendChild(span);
        _mainWindow.$find("advFind").set_entityName(oldEntityName);
    } else
        window.setTimeout(FetchXmlAdvancedFindShowResults, 100);
}

var oldEntityName = "";
var entityName = "";
var objectTypeCode = -1;
var sFetchXml = "";